package com.neusoft.yiyang.bed.controller;

import com.neusoft.yiyang.common.entity.bed.Bed;
import com.neusoft.yiyang.bed.service.BedService;
import com.neusoft.yiyang.common.entity.bed.vto.BedCustomer;
import com.neusoft.yiyang.common.entity.bed.vto.BedCustomerUsage;
import com.neusoft.yiyang.common.enums.BedStatus;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.web.bind.annotation.*;

import java.util.*;
import java.util.stream.Collectors;

@Tag(name = "床位管理接口", description = "床位的CRUD、查询、状态管理等操作")
@RestController
@RequestMapping("/beds")
public class BedController {

    @Autowired
    private BedService bedService;

    @Operation(summary = "创建床位", description = "新增床位信息（如楼栋、楼层、房间号等）")
    @PostMapping
    public void createBed(
            @Parameter(description = "床位信息", required = true) @RequestBody Bed bed) {
        bedService.createBed(bed);
    }

    @Operation(summary = "更新床位信息", description = "修改床位的基本信息（支持部分字段更新）")
    @PutMapping("/{id}")
    public void updateBed(
            @Parameter(description = "床位ID", required = true) @PathVariable Integer id,
            @Parameter(description = "更新后的床位信息", required = true) @RequestBody Bed bed) {
        bed.setBedId(id);
        bedService.updateBed(bed);
    }

    @Operation(summary = "删除床位", description = "逻辑删除床位（不会物理删除，仅标记为删除状态）")
    @DeleteMapping("/{id}")
    public void deleteBed(
            @Parameter(description = "床位ID", required = true) @PathVariable Integer id) {
        bedService.deleteBed(id);
    }

    @Operation(summary = "根据ID查询床位", description = "获取指定ID的床位详细信息")
    @GetMapping("/{id}")
    public Bed getBed(
            @Parameter(description = "床位ID", required = true) @PathVariable Integer id) {
        return bedService.getBedById(id);
    }

    @Operation(summary = "查询所有床位", description = "获取系统中所有床位的信息（包含各种状态）")
    @GetMapping("all")
    public List<Bed> getAllBeds() {
        return bedService.getAllBeds();
    }

    @Operation(summary = "查询所有空闲床位", description = "获取状态为'空闲'（free）的床位列表")
    @GetMapping("getAllFreeBeds")
    public List<Bed> getAllFreeBeds() {
        return bedService.getAllFreeBeds();
    }

    @Operation(summary = "批量查询床位", description = "根据床位ID列表查询多个床位信息")
    @GetMapping("getByBedIds")
    public List<Bed> getByBedIds(
            @Parameter(description = "床位ID列表（多个ID用逗号分隔）", required = true)
            @RequestParam List<Integer> bedIds) {
        return bedService.getByBedIds(bedIds);
    }

    @Operation(summary = "查询特定楼层的床位及客户信息", description = "获取指定楼层的床位及其分配的客户信息")
    @GetMapping("/selectbyfloor")
    public List<BedCustomer> getBedUsageByFloorId(
            @Parameter(description = "楼层号（如1、2、3）", required = true)
            @RequestParam Integer selectedFloor) {
        return bedService.getBedCustomerByFloor(selectedFloor);
    }

    @Operation(summary = "查询在用/已迁出床位记录", description = "获取状态为'在用'（occupied）或'已迁出'（out）的床位使用记录")
    @GetMapping("/getAllBedCutomerUsageOutOccupied")
    public List<BedCustomerUsage> getAllBedCutomerUsageOutOccupied() {
        return bedService.getAllBedCustomerUsageOutOccupied();
    }

    @Operation(summary = "查询所有床位使用记录", description = "获取系统中所有床位的使用记录（包含所有状态）")
    @GetMapping("/getAllBedCutomerUsage")
    public List<BedCustomerUsage> getAllBedCutomerUsage() {
        return bedService.getAllBedCutomerUsage();
    }

    @Operation(summary = "筛选在用/已迁出床位记录", description = "根据状态、客户名、入住日期筛选床位使用记录")
    @GetMapping("/getBedCutomerUsageOutOccupied")
    public List<BedCustomerUsage> getBedCutomerUsageOutOccupied(
            @Parameter(description = "状态（可选，out=已迁出，occupied=在用）") @RequestParam(required = false) String status,
            @Parameter(description = "客户姓名（可选，支持模糊匹配）") @RequestParam(required = false) String customerName,
            @Parameter(description = "入住日期（可选，格式：yyyy-MM-dd）")
            @RequestParam(required = false) @DateTimeFormat(pattern = "yyyy-MM-dd") Date checkInDate
    ) {
        List<BedCustomerUsage> bedCustomerUsages = bedService.getAllBedCustomerUsageOutOccupied();
        return bedCustomerUsages.stream()
                .filter(usage -> {
                    boolean statusMatch = status == null || status.isEmpty() || usage.getStatus().toString().equals(status);
                    boolean nameMatch = customerName == null || customerName.isEmpty() ||
                            (usage.getCustomerName() != null && usage.getCustomerName().contains(customerName));
                    boolean dateMatch = checkInDate == null ||
                            (usage.getCheckInDate() != null && usage.getStartDate().equals(checkInDate));
                    return statusMatch && nameMatch && dateMatch;
                })
                .collect(Collectors.toList());
    }

    @Operation(summary = "根据楼层获取房间号", description = "获取指定楼层的所有房间号（用于下拉选择）")
    @GetMapping("/rooms")
    public List<Map<String, String>> getRoomsByFloor(
            @Parameter(description = "楼层号（如1、2、3）", required = true) @RequestParam Integer floor) {
        Integer buildingNo = 606; // 固定为606号楼
        List<String> rooms = bedService.getDistinctRoomsByFloor(buildingNo, floor);
        return rooms.stream()
                .sorted()
                .map(room -> {
                    Map<String, String> item = new HashMap<>();
                    item.put("label", room);
                    item.put("value", room);
                    return item;
                })
                .collect(Collectors.toList());
    }

    @Operation(summary = "获取房间内可用床位", description = "查询指定楼栋、楼层、房间内的空闲床位（状态为free）")
    @GetMapping("/available-beds")
    public List<Map<String, String>> getAvailableBeds(
            @Parameter(description = "楼栋号（如606）", required = true) @RequestParam Integer buildingNo,
            @Parameter(description = "楼层号", required = true) @RequestParam Integer floor,
            @Parameter(description = "房间号（如101）", required = true) @RequestParam String roomNumber) {

        List<Bed> beds = bedService.getAvailableBedsByRoom(buildingNo, floor, roomNumber);
        return beds.stream()
                .sorted(Comparator.comparingInt(Bed::getBedNo))
                .map(bed -> {
                    Map<String, String> item = new HashMap<>();
                    item.put("label", bed.getBedNo().toString());
                    item.put("value", bed.getBedNo().toString());
                    return item;
                })
                .collect(Collectors.toList());
    }

    @Operation(summary = "占用床位", description = "将指定床位状态改为'在用'（occupied）")
    @GetMapping("/occupy")
    public int occupyBed(
            @Parameter(description = "楼栋号", required = true) @RequestParam("buildingNo") Integer buildingNo,
            @Parameter(description = "楼层号", required = true) @RequestParam("floor") Integer floor,
            @Parameter(description = "房间号", required = true) @RequestParam("roomNumber") String roomNumber,
            @Parameter(description = "床位号", required = true) @RequestParam("bedNo") Integer bedNo
    ) {
        Bed bed = bedService.getBedByParams(buildingNo, floor, roomNumber, bedNo);
        bed.setStatus(BedStatus.occupied);
        bedService.updateBed(bed);
        return bed.getBedId();
    }

    @Operation(summary = "搜索床位", description = "根据楼栋、楼层、房间号筛选床位")
    @GetMapping("/search")
    public List<Bed> searchBeds(
            @Parameter(description = "楼栋号（可选）") @RequestParam(required = false) Integer buildingNo,
            @Parameter(description = "楼层号（可选）") @RequestParam(required = false) Integer floor,
            @Parameter(description = "房间号（可选）") @RequestParam(required = false) String roomNumber) {
        return bedService.searchBeds(buildingNo, floor, roomNumber);
    }

    @Operation(summary = "查询有空闲床位的楼层", description = "获取存在空闲床位的楼层号列表")
    @GetMapping("/getFreeFloor")
    public List<Integer> getFreeFloor() {
        return bedService.getFreeFloor();
    }

    @Operation(summary = "查询楼层内有空闲床位的房间", description = "获取指定楼层中存在空闲床位的房间号列表")
    @GetMapping("/getFreeRoom")
    public List<String> getFreeRoom(
            @Parameter(description = "楼层号", required = true) @RequestParam Integer floorNumber) {
        return bedService.getFreeRoom(floorNumber);
    }

    @Operation(summary = "查询房间内的空闲床位号", description = "获取指定房间内的空闲床位号列表")
    @GetMapping("/getFreeBed")
    public List<Integer> getFreeBed(
            @Parameter(description = "房间号", required = true) @RequestParam String roomNumber) {
        return bedService.getFreeBed(roomNumber);
    }

    @Operation(summary = "根据位置查询床位ID", description = "通过楼栋、楼层、房间号、床位号查询对应的床位ID")
    @GetMapping("/query")
    public Integer getBedIdByLocation(
            @Parameter(description = "楼栋号", required = true) @RequestParam Integer buildingNo,
            @Parameter(description = "楼层号", required = true) @RequestParam Integer floor,
            @Parameter(description = "房间号", required = true) @RequestParam String roomNumber,
            @Parameter(description = "床位号", required = true) @RequestParam Integer bedNo
    ) {
        return bedService.getBedIdByLocation(buildingNo, floor, roomNumber, bedNo);
    }

    @Operation(summary = "更新床位信息（重载）", description = "通过请求体更新床位信息（无需路径ID，ID包含在请求体中）")
    @PutMapping("update")
    public void updateBed2(
            @Parameter(description = "床位信息（含ID）", required = true) @RequestBody Bed bed) {
        bedService.updateBed(bed);
    }
}